import { useState, useRef } from 'react';
import TaskList from '../components/TaskList';
import toast from 'react-hot-toast';

const Home = () => {
   const ref = useRef(null);
   const [word, setWord] = useState('');
   const handleChangeInput = (e) => {
      const value = e.target.value;
      setWord(value);
   };

   const handleSubmit = () => {
      if (word === '') return toast.error('任务名称不能为空');
      ref.current.addTask(word).then(() => {
         setWord('');
      });
   };

   return (
      <div className="mt-12">
         <div className="max-w-lg mx-auto">
            {/* Task Manager */}
            <section className="box flex flex-col items-center">
               <h2 className="text-2xl mb-6 font-bold">Task Manager</h2>
               {/* Task Editor */}
               <div className="flex w-full">
                  <input
                     value={word}
                     className="grow rounded-l"
                     placeholder="e.g. wash dishes"
                     onChange={handleChangeInput}
                  />
                  <button
                     className="btn rounded-r bg-indigo-600 hover:bg-indigo-800"
                     onClick={handleSubmit}
                  >
                     Submit
                  </button>
               </div>
            </section>
            <TaskList ref={ref} />
         </div>
      </div>
   );
};

export default Home;
